package com.ruoyi.contract.utils;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSON;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * Created by zhangxiang on 2019/12/25.
 */
public class RestfulUtils {

    //代理地址IP
    private final static String ip="10.197.33.198";
//    private final static String ip="10.197.33.186";

    //代理地址端口
    private final static int port = 1180;

    public static JSONObject doGet(String url){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
//        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//        headers.setContentType(type);
        HttpEntity<String> entity = new HttpEntity<String>(headers);
        RestTemplate restTemplate = new RestTemplate();
        //SimpleClientHttpRequestFactory reqfac = new SimpleClientHttpRequestFactory();
        //reqfac.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port)));
        //restTemplate.setRequestFactory(reqfac);
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        String strbody = restTemplate.exchange(url, HttpMethod.GET,entity,String.class).getBody();
        return JSON.parseObject(strbody);
    }

    public static JSONObject doPost(String url,JSONObject data){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        RestTemplate restTemplate = new RestTemplate();
        //SimpleClientHttpRequestFactory reqfac = new SimpleClientHttpRequestFactory();
        //reqfac.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port)));
        //restTemplate.setRequestFactory(reqfac);
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpEntity<Object> entity = new HttpEntity<Object>(data, headers);
        String result = restTemplate.postForObject(url, entity, String.class);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = JSON.parseObject(result);
        }catch (Exception e){
            jsonObject.put("result",result);
        }finally {
            return jsonObject;
        }
    }
}
